<template>
	<div class="shuXingMuBan">
		<div class="bfff left-bottom">
			<el-form inline label-width="90px">
				<el-form-item label="模型标题：">
					<el-input
						type="text"
						v-model="model.modelName"
						placeholder="请输入模型标题..."
						@keyup.enter.native="modelSearch"
					/>
				</el-form-item>
				<el-form-item label="编码：" class="disNo">
					<el-input
						type="text"
						v-model="model.modelCode"
						placeholder="请输入模型编码..."
						@keyup.enter.native="modelSearch"
					/>
				</el-form-item>
				<el-form-item label="状态：">
					<el-select v-model="model.modelStatus" class="m-2" placeholder="请选择状态...">
						<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button class="primary" type="primary" @click="modelSearch" v-auth="['kb:kbModel:save']">
						搜索
					</el-button>
					<el-button type="primary" plain @click="resetting">重置</el-button>
				</el-form-item>
			</el-form>
			<div class="btnx">
				<el-button type="primary" :size="large" @click="setShowMore" v-auth="['kb:kbModel:save']">
					+新增
				</el-button>
			</div>
			<div class="table-scrol">
				<div class="table">
					<el-table :data="tableData" style="width: 100%">
						<el-table-column
							align="center"
							prop="name"
							label="模型标题"
							show-overflow-tooltip
							min-width="200"
						/>
						<el-table-column
							align="center"
							prop="code"
							label="模型编码"
							show-overflow-tooltip
							min-width="120"
						>
							<template #default="{ row }">
								<el-button text="primary" type="primary" @click="copyCode(row.code)">
									{{ row.code }}</el-button
								>
							</template>
						</el-table-column>
						<el-table-column align="center" prop="status" label="状态" min-width="100">
							<template #default="{ row }">
								<el-switch
									@change="onState(row)"
									v-model="row.status"
									:active-value="qiyong"
									:inactive-value="jinyong"
								/>
								<!-- <span>启用</span> -->
								<span v-if="row.status == '1'" class="f14 c60 ml15">启用</span>
								<span v-else class="f14 c60 ml15">未启用</span>
							</template>
						</el-table-column>
						<el-table-column align="center" prop="k5" label="操作" min-width="160">
							<template #default="{ row }">
								<div class="table-color">
									<el-button
										plain
										:icon="View"
										@click="details(row)"
										v-auth="['kb:kbModel:info', 'knowledge:kbModelLabel:pageList']"
									></el-button>
									<el-button
										plain
										:icon="EditPen"
										@click="editList(row)"
										v-auth="['kb:kbModel:edit']"
									></el-button>
									<el-button
										plain
										:icon="Delete"
										v-auth="['kb:kbModel:delete']"
										@click="delModel(row)"
									></el-button>
								</div>
							</template>
						</el-table-column>
						<template #empty>
							<el-empty description="暂无数据" />
						</template>
					</el-table>
				</div>
				<br />
				<div style="display: flex; justify-content: center">
					<v-pagination
						:total="total"
						v-model:size="pageSizes"
						v-model:page="current"
						@pagination="fetchList"
						@paginations="fetchLists"
					></v-pagination>
				</div>
			</div>
		</div>
		<!-- 新增模板 -->
		<el-dialog
			v-model="dialogVisible"
			class="dialog"
			:title="zt"
			:close-on-click-modal="false"
			:show-close="false"
			destroy-on-close="true"
		>
			<template #header="{ close, titleId, titleClass }">
				<div class="dialog-header center btheme cfff">
					<div class="flex f16">新增模板</div>
					<el-icon class="pointer" size="20" color="#fff" @click="xq">
						<Close />
					</el-icon>
				</div>
			</template>
			<el-steps :active="active" finish-status="success" simple style="margin-top: 20px">
				<el-step title="基本配置"></el-step>
				<el-step title="字段配置"></el-step>
			</el-steps>
			<el-row>
				<div class="contents" v-if="active == 1">
					<el-form :model="form" ref="formRef" :rules="rules" label-width="100px">
						<el-form-item prop="modelName" label="模型标题：">
							<el-input
								v-model="form.modelName"
								placeholder="请输入模型标题"
								maxlength="20"
								show-word-limit
							></el-input>
						</el-form-item>
						<el-form-item label="状态：">
							<el-switch
								v-model="form.status"
								:active-value="qiyong"
								:inactive-value="jinyong"
								active-color="#409eff"
								inactive-color="#c0c4cc"
								active-text="启用"
								inactive-text="未启用"
							>
							</el-switch>
						</el-form-item>
					</el-form>
				</div>
				<div class="contents" v-if="active == 2">
					<div style="margin-bottom: 20px">
						<el-button style="width: 100%" type="primary" :disabled="views" plain @click="addData"
							>新增一条</el-button
						>
					</div>
					<el-table border :data="tableDatas" style="width: 100%">
						<el-table-column prop="name" label="字段标题" width="180">
							<template #default="{ row }">
								<el-input :disabled="views" v-model="row.name"></el-input>
							</template>
						</el-table-column>
						<el-table-column label="表单类型" width="260">
							<template #default="{ row }">
								<div class="set">
									<el-select v-model="row.formType">
										<el-option
											:disabled="views"
											v-for="item in option"
											:key="item.code"
											:label="item.name"
											:value="+item.code"
										>
										</el-option>
									</el-select>
									<el-button type="text" @click="setFn(row)" v-if="row.formType == 5">设置</el-button>
								</div>
							</template>
						</el-table-column>
						<el-table-column label="是否必填">
							<template #default="{ row }">
								<el-switch
									:disabled="views"
									v-model="row.isRequired"
									:active-value="qiyong"
									:inactive-value="jinyong"
									active-color="#409eff"
									inactive-color="#c0c4cc"
								>
								</el-switch>
								<span v-if="row.isRequired == '1'" style="margin-left: 10px">是</span>
								<span v-else style="margin-left: 10px">否</span>
							</template>
						</el-table-column>
						<el-table-column label="启用状态">
							<template #default="{ row }">
								<el-switch
									:disabled="views"
									v-model="row.status"
									:active-value="qiyong"
									:inactive-value="jinyong"
									active-color="#409eff"
									inactive-color="#c0c4cc"
								>
								</el-switch>
								<span v-if="row.status == '1'" style="margin-left: 10px">是</span>
								<span v-else style="margin-left: 10px">否</span>
							</template>
						</el-table-column>
						<el-table-column label="是否支持搜索">
							<template #default="{ row }">
								<div v-if="row.formType != 3 && row.formType != 4">
									<el-switch
										:disabled="views"
										v-model="row.isFiltrate"
										:active-value="qiyong"
										:inactive-value="jinyong"
										active-color="#409eff"
										inactive-color="#c0c4cc"
									>
									</el-switch>
									<span v-if="row.isFiltrate == '1'" style="margin-left: 10px">启用</span>
									<span v-else style="margin-left: 10px">未启用</span>
								</div>
							</template>
						</el-table-column>
						<el-table-column label="操作">
							<template #default="row">
								<el-popover
									placement="right"
									:visible="popoverVisible[row.$index]"
									:width="160"
									trigger="click"
								>
									<template #reference>
										<el-button
											:disabled="views"
											type="primary"
											:icon="Delete"
											@click="popoverVisible[row.$index] = true"
										></el-button>
									</template>
									<div>
										<div class="delTable">
											<span> 是否确认删除</span>
											<span @click="popoverVisible[row.$index] = false" class="delTable-x"
												>x</span
											>
										</div>
										<div>
											<el-button @click="popoverVisible[row.$index] = false">否</el-button>
											<el-button type="primary" @click="handleDelete(row.$index)">是</el-button>
										</div>
									</div>
								</el-popover>
							</template>
						</el-table-column>
					</el-table>
				</div>
			</el-row>
			<el-dialog
				v-model="innerVisible"
				:close-on-click-modal="false"
				width="500px"
				:title="selectTitle"
				append-to-body
			>
				<div class="dialog-content">
					<el-form :model="ruleFormList" class="demo-ruleForm" status-icon>
						<div class="center" v-for="(v, i) in selectList">
							<div class="flex">
								<el-form-item label="下拉列表" prop="name">
									<el-input
										class="name"
										v-model="v.name"
										placeholder="请输入下拉列表"
										maxlength="20"
										show-word-limit
										:disabled="views"
									/>
								</el-form-item>
							</div>
							<div class="icon pointer" v-if="!views">
								<el-icon @click="removeSelect(i)" size="18" color="#2972FA" v-if="i != 0">
									<CircleCloseFilled />
								</el-icon>
							</div>
						</div>

						<!-- <el-form-item label="" >
							<div class="center">
								<div class="el-form-item__label"></div>
							</div>
						</el-form-item> -->
					</el-form>
					<div v-if="selectTitle == '新增下拉列表' || selectTitle == '编辑下拉列表'">
						<el-button @click="addSelectFn()" type="primary" plain :icon="CirclePlusFilled" class="flex"
							>新增一条</el-button
						>
						<el-button type="primary" @click="analysisClick" plain :icon="Finished" class="flex"
							>解析模板</el-button
						>
					</div>
				</div>
				<template #footer>
					<div class="dialog-footer">
						<el-button @click="closes">取消</el-button>
						<el-button type="primary" @click="onConfirm"> 确定 </el-button>
					</div>
				</template>
			</el-dialog>
			<div class="button">
				<el-button @click="xq">取消</el-button>
				<el-button v-if="active == 1" @click="onTwo" type="primary">下一步</el-button>
				<el-button v-else @click="onOne" v-if="!views">上一步</el-button>
				<el-button v-if="active == 2" @click="onSubmit" type="primary">确定</el-button>
			</div>
		</el-dialog>
		<el-dialog
			v-model="analysis"
			title="解析模板"
			width="500px"
			:close-on-click-modal="false"
			:destroy-on-close="true"
		>
			<span>提示：请输入JSON格式</span>
			<div class="analysis">
				<el-input
					v-model="analysisText"
					type="textarea"
					:autosize="{ minRows: 4, maxRows: 6 }"
					placeholder='请输入JSON格式，例如：[{"name":"value"}]'
					clearable
				/>
			</div>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="analysisCancellation">取消</el-button>
					<el-button type="primary" @click="analysisYes">确定</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
import { View, EditPen, Delete, CirclePlusFilled, Finished } from "@element-plus/icons-vue"
import { useDictStore } from "/store/dict"
import { ElMessage, ElMessageBox } from "element-plus"
import { postAxios } from "/axios"
import { useRouter } from "vue-router"
const { proxy } = getCurrentInstance()
const route = useRoute()
const router = useRouter()
const total = ref(0)
const current = ref(1)

const innerVisible = ref(false)
const selectList = ref([
	{
		name: "",
	},
])
const analysis = ref(false)
const ruleFormList = reactive({
	region: "",
})
const selectTitle = ref("新增下拉列表")
// 删除
const removeSelect = index => {
	selectList.value.splice(index, 1)
}

const closes = () => {
	innerVisible.value = false
	selectList.value = [
		{
			name: "",
		},
	]
}

const selectJson = ref("")
const setShowMore = () => {
	zt.value = "新增模板"
	selectTitle.value = "新增下拉列表"
	views.value = false
	active.value = 1
	dialogVisible.value = !dialogVisible.value
	selectList.value = [
		{
			name: "",
		},
	]
	getCread()
}
async function getList() {
	const res = await getAxios("/kb/kbModel/page?current=1&size=10")
	total.value = +res.total
	tableData.value = res.records
}
getList()
function onConfirm() {
	// todo
	currentRow.value.selectFrame = selectList.value
	if (!selectList.value[0].name) {
		ElMessage.error("下拉列表至少填一个")
		return
	}
	innerVisible.value = false
}
// 新增
const addSelectFn = () => {
	// if (selectList.value.length < 10) {
	selectList.value.push({
		name: "",
	})
	// } else {
	// ElMessage.error("一次最多只能增加10条")
	// }
}
const currentRow = ref({})
// 点设置 打开弹窗
function setFn(row) {
	currentRow.value = row
	if (row.selectFrame) {
		selectList.value = row.selectFrame || [
			{
				name: "",
			},
		]
	} else {
		selectList.value = [
			{
				name: "",
			},
		]
	}
	innerVisible.value = true
}

// 下拉框选项
const options = [
	{
		value: "1",
		label: "启用",
	},
	{
		value: "2",
		label: "未启用",
	},
]
const tableData = ref([])
// 控制弹窗
const dialogVisible = ref(false)
const popoverVisible = ref([])
//查看
const views = ref(true)
const option = ref([])
const qiyong = ref(1)
const jinyong = ref(2)
const jin = ref([])
//子菜单
const tableDatas = ref([
	// {
	// 	name: "", //字段标题
	// 	status: 2, //状态
	// 	sort: 1, //排序状态
	// 	isRequired: 2, //必填
	// 	formType: null, //表单类型
	// 	isFiltrate: 2, //搜索
	// },
])
let active = ref(1)
const analysisText = ref("")
let form = reactive({
	modelName: "",
	// modelCode: "",
	status: 2,
})
const activeIndex = ref(1)

// 复制模型编码
const copyCode = text => {
	var aux = document.createElement("input")
	aux.setAttribute("value", text)
	document.body.appendChild(aux)
	aux.select()
	document.execCommand("copy")
	document.body.removeChild(aux)
	ElMessage({
		message: "复制成功",
		type: "success",
	})
}

async function getCread() {
	option.value = await useDictStore().getDict("/system/enums/list?enumName=FromType&moduleName=knowledge")
}

// 下一步
const onTwo = async () => {
	try {
		await formRef.value?.validate()
		active.value = 2
		if (zt.value == "新增模板" && tableDatas.value.length < 1) {
			tableDatas.value.push({
				name: "", //字段标题
				status: 2, //状态
				// sort: tableDatas.value.length + 1, //排序状态
				isRequired: 2, //必填
				formType: null, //表单类型
				isFiltrate: 2, //搜索
			})
		}
	} catch (error) {
		return
	}
	popoverVisible[tableDatas.value.length - 1] = false
}
const onState = async row => {
	try {
		await postAxios("/kb/kbModel/updateStatus", row)
	} catch (error) {
		row.status = 1
		ElMessage.error(error)
	}
}
//删除
const handleDelete = index => {
	if (tableDatas.value.length > 1) {
		tableDatas.value.splice(index, 1)
	} else {
		ElMessage.error("最少保留一条")
	}
	popoverVisible.value[index] = false
}
//取消
const xq = () => {
	if (active.value == 1) {
		formRef.value.resetFields()
	}
	dialogVisible.value = false
	active.value = 1
	tableDatas.value = [
		{
			name: "", //字段标题
			status: 2, //状态
			// sort: tableDatas.value.length + 1, //排序状态
			isRequired: 2, //必填
			formType: null, //表单类型
			propName: `col_${tableDatas.value.length + 1}`,
			isFiltrate: 2, //搜索
		},
	]
	params()
}
//效验
const rules = reactive({
	modelName: [{ required: true, message: "请输入模型标题", trigger: "blur" }],
})

const addData = () => {
	tableDatas.value.push({
		name: "", //字段标题
		status: 2, //状态
		// sort: tableDatas.value.length + 1, //排序状态
		isRequired: 2, //必填
		formType: null, //表单类型
		propName: `col_${tableDatas.value.length + 1}`,
		isFiltrate: 2, //搜索
	})
	popoverVisible[tableDatas.value.length - 1] = false
}
const model = reactive({
	modelName: "",
	modelCode: "",
	modelStatus: "",
})

let sta = false
const formRef = ref()
// 提交表单
const onSubmit = async () => {
	try {
		await formRef.value?.validate()
	} catch (error) {
		return
	}
	let tableStatus = []
	sta = false
	for (let i = 0; i < tableDatas.value.length; i++) {
		tableStatus.push(tableDatas.value[i].status)
		if (tableDatas.value[i].name == "") {
			sta = true
		}
		if (tableDatas.value[i].formType == null) {
			sta = true
		}
	}
	if (tableStatus.every(currentValue => currentValue == 2)) {
		return ElMessage.error("启用状态至少启用一项")
	} else {
		let obj = {
			status: form.status,
		}
		if (!sta) {
			if (zt.value == "新增模板") {
				obj.modelName = form.modelName
				obj.propCols = tableDatas.value
				try {
					await postAxios("/kb/kbModel/save", {
						...obj,
					})
					dialogVisible.value = false
					active.value = 1
					ElMessage.success("新增成功")
					tableDatas.value = [
						{
							name: "", //字段标题
							status: 2, //状态
							// sort: tableDatas.value.length + 1, //排序状态
							isRequired: 2, //必填
							formType: null, //表单类型
							propName: `col_${tableDatas.value.length + 1}`,
							isFiltrate: 2, //搜索
						},
					]
					getList()
					params()
				} catch (error) {
					ElMessag.error(error)
				}
			} else if (zt.value == "编辑模板") {
				obj.name = form.modelName
				obj.cols = tableDatas.value
				obj.id = bId.value
				obj.code = code.value
				try {
					await postAxios("/kb/kbModel/edit", {
						...obj,
					})
					dialogVisible.value = false
					active.value = 1
					ElMessage.success("修改成功")
					tableDatas.value = [
						{
							name: "", //字段标题
							status: 2, //状态
							// sort: tableDatas.value.length + 1, //排序状态
							isRequired: 2, //必填
							formType: null, //表单类型
							propName: `col_${tableDatas.value.length + 1}`,
							isFiltrate: 2, //搜索
						},
					]
					getList()
					params()
				} catch (error) {
					ElMessage.error(error)
					form.status = 1
				}
			} else if (zt.value == "查看详情") {
				dialogVisible.value = false
				active.value = 1
			}
		} else {
			ElMessage.error("字段标题和表单类型不能为空")
		}
	}
}
watch(tableDatas.value, () => {
	tableDatas.value.forEach((item, index) => {
		if (item.formType == 3 || item.formType == 4) {
			jin.value[index] = "1"
		}
	})
})
//搜索
const modelSearch = async () => {
	try {
		const obj = {}
		if (model.modelName != "") {
			obj.name = model.modelName
		}
		if (model.modelCode != "") {
			obj.code = model.modelCode
		}
		if (model.modelStatus != "") {
			obj.status = model.modelStatus
		}
		const res = await getAxios("/kb/kbModel/page", obj)
		tableData.value = res.records
		total.value = +res.total
		// model.modelName = ""
		// model.modelCode = ""
		// model.modelStatus = ""
		current.value = "1"
	} catch (error) {
		ElMessage.error(error)
	}
}
//清空表单
function params() {
	tableDatas.value.splice(1)
	form.modelName = ""
	form.status = 2
	tableDatas.value[0].name = ""
	tableDatas.value[0].formType = null
	tableDatas.value[0].isRequired = 2
	// tableDatas.value[0].sort = 1
	tableDatas.value[0].status = 2
	tableDatas.value[0].isFiltrate = 2
}

//重置
const resetting = async () => {
	model.modelName = ""
	model.modelCode = ""
	model.modelStatus = ""
	getList()
}
//详情
const details = async row => {
	zt.value = "查看详情"
	selectTitle.value = "查看下拉列表"
	views.value = true
	const { cols } = await getAxios(`/kb/kbModel/info?id=${row.id}`)
	active.value = 2
	dialogVisible.value = true
	tableDatas.value = cols
	getCread()
}
const delModel = async row => {
	ElMessageBox.confirm("是否确认删除", "提示", {
		confirmButtonText: "确定",
		cancelButtonText: "取消",
		type: "warning",
	}).then(async () => {
		try {
			await postAxios(`/kb/kbModel/delete?id=${row.id}`)
			ElMessage.success("删除成功")
			getList()
		} catch (error) {
			ElMessage.error(error)
		}
	})
}
const zt = ref("")
const bId = ref("")
const code = ref("")
const editList = async row => {
	getCread()
	bId.value = row.id
	code.value = row.code
	zt.value = "编辑模板"
	selectTitle.value = "编辑下拉列表"
	dialogVisible.value = true
	views.value = false
	const res = await getAxios(`/kb/kbModel/info?id=${row.id}`)
	tableDatas.value = res.cols
	form.modelName = res.name
	form.status = res.status
}

const fetchList = async val => {
	current.value = val
	const res = await getAxios(`/kb/kbModel/page?current=${val}&size=${pageSizes.value}`)
	total.value = +res.total
	tableData.value = res.records
}
const pageSizes = ref(10)
const fetchLists = async val => {
	pageSizes.value = val
	const res = await getAxios(`/kb/kbModel/page?current=${current.value}&size=${val}`)
	total.value = +res.total
	tableData.value = res.records
}
const analysisClick = () => {
	analysis.value = true
}
//解析模板取消
const analysisCancellation = () => {
	analysisText.value = ""
	analysis.value = false
}
//解析模板确定
const analysisYes = () => {
	try {
		let analysisList = JSON.parse(analysisText.value)
		analysisList.forEach(item => {
			let selectListIf = false
			selectList.value.forEach(it => {
				if (it && it.name == Object.values(item)[0]) {
					selectListIf = true
				}
			})
			if (!selectListIf) {
				if (selectList.value[selectList.value.length - 1].name == "") {
					selectList.value[selectList.value.length - 1] = {
						name: Object.values(item)[0],
					}
				} else {
					selectList.value.push({
						name: Object.values(item)[0],
					})
				}
			}
		})
		analysisText.value = ""
		analysis.value = false
	} catch (error) {
		ElMessage.error("请输入正确的格式")
	}
}
const onOne = () => {
	active.value = 1
}
</script>
<style lang="scss" scoped>
@import "/style/basis";
.shuXingMuBan {
	background-color: #f8f8f8;
	padding: 25px;
	.primary {
		width: 65px;
		height: 30px;
		border-radius: 3px;
	}
	:deep(.el-step__head.is-success) {
		color: #ff952c !important;
		border-color: #ff952c !important;
	}

	:deep(.el-step__title.is-success) {
		color: #ff952c !important;
	}

	.left-bottom {
		padding: 30px;
		.btnx {
			padding: 0 0 20px 0;
		}

		.table-head {
			.primary {
				margin-left: 15px;
				@include maxWidth(900) {
					margin-left: 5px;
				}
			}

			.danger {
				color: #ff952c;
			}
		}

		:deep(.el-table) {
			border: 1px solid #eceef5;
		}

		:deep(.el-table th.el-table__cell) {
			background-color: #f4f7fa;
		}

		:deep(.el-table .el-table__cell) {
			height: 50px;
			color: #606266;
		}
	}
}
.contents {
	margin-top: 20px;
	width: 100%;
	height: 500px;
	padding: 20px;
	overflow-y: auto;
}
.button {
	padding: 20px;
	display: flex;
	justify-content: flex-end;
}
.el-dropdown-link {
	cursor: pointer;
	color: #409eff;
}
.el-icon-arrow-down {
	font-size: 12px;
}
.delTable {
	display: flex;
	justify-content: space-between;
	margin-bottom: 20px;
	.delTable-x {
		cursor: pointer;
	}
}
:deep(.el-input--small) {
	@include maxWidth(950) {
		width: 150px;
	}
	@include maxWidth(850) {
		width: 120px;
	}
}
.disNo {
	@include maxWidth(768) {
		display: none;
	}
}
.button-s {
	@include maxWidth(569) {
		margin-top: 1vh;
	}
}
.state-dis {
	display: flex;
	@include maxWidth(435) {
		margin-top: 1vh;
	}
}
:deep(.dialog) {
	width: 1000px !important;
}
.text-item {
	line-height: 2;
}
.table-color {
	:deep(.el-button) {
		&:focus {
			color: #606266;
			background-color: #fff;
			border: 1px solid #dcdfe6;
		}
	}
}

.icon {
	width: 20px;
	margin-bottom: 10px;
}
.set {
	display: flex;
	align-items: center;
	gap: 10px;
	:deep(.el-select) {
		width: 190px;
	}
}
.analysis {
	margin-top: 20px;
}
.dialog-content {
	.demo-ruleForm {
		max-height: 600px;
		overflow-y: scroll;
	}
}
</style>
